package common

import (
	"fmt"
	"log/slog"
	"net"
	"strconv"
	"sync"

	"github.com/spf13/viper"
)

var viperConfig *viper.Viper

func InitConfig(filename string) *viper.Viper {

	if filename == "dm.yaml" {
		//workDir, _ := os.Getwd()
		viper.AddConfigPath(".")      // 配置文件的路径
		viper.SetConfigName(filename) // 配置文件名 (不带扩展格式)
		viper.SetConfigType("yaml")   // 如果你的配置文件没有写扩展名，那么这里需要声明你的配置文件属于什么格式

	} else {
		// 指定配置文件（路径 + 配置文件名）
		viper.SetConfigFile(filename)
	}

	//fmt.Println(workDir)

	err := viper.ReadInConfig() //找到并读取配置文件
	if err != nil {             // 捕获读取中遇到的error
		panic(fmt.Errorf("fatal error config file:%w", err))
	}
	return viper.GetViper()

}

type DMConfig struct {
	User       string `yaml:"user"`
	Password   string `yaml:"password"`
	Host       string `yaml:"host"`
	Port       int    `yaml:"port"`
	BackupPath string `yaml:"backup_path"`
}
type Config struct {
	Sections map[string]DMConfig
}

type DMConfigHandler struct {
	sync.RWMutex
	Config *Config
}

// 获取全局配置
func (ch *DMConfigHandler) GetConfig() *Config {
	ch.RLock()
	defer ch.RUnlock()
	return ch.Config
}

// 加载配置文件
func (ch *DMConfigHandler) ReloadConfig(filename string, logger *slog.Logger) error {
	//var host, port string
	config := &Config{}
	m := make(map[string]DMConfig)
	viperConfig = InitConfig(filename)
	viperConfig.Unmarshal(&m)
	//过滤无效配置块
	for k, v := range m {
		if err := v.validateConfig(); err != nil {
			logger.Error("section failed to validate config", "section", k, "error", err)
			delete(m, k)
		}
	}
	config.Sections = m
	if len(config.Sections) == 0 {
		return fmt.Errorf("no configuration found")
	}
	ch.Lock()
	ch.Config = config
	ch.Unlock()
	return nil
}

// 校验达梦配置文件
func (d DMConfig) validateConfig() error {
	if d.User == "" {
		return fmt.Errorf("no user specified in section or parent")
	}
	if d.Password == "" {
		return fmt.Errorf("no password specified in section or parent")
	}
	return nil
}

// 生成DSN
func (d DMConfig) FormDSN(target string) (string, error) {

	if target == "" {
		host := "127.0.0.1"
		port := "5236"
		if d.Host != "" {
			host = d.Host
		}
		if d.Port != 0 {
			port = strconv.Itoa(d.Port)
		}
		return fmt.Sprintf("dm://%s:%s@%s:%v", d.User, d.Password, host, port), nil
	} else {
		if _, _, err := net.SplitHostPort(target); err != nil {
			return "", fmt.Errorf("failed to parse target: %s", err)
		}
		return fmt.Sprintf("dm://%s:%s@%s", d.User, d.Password, target), nil
	}

}

// // 校验配置文件
// func validateConfig(v *viper.Viper) error {
// 	return nil
// }
